
<template>
  <div class="shipment">
    <div style="position: relative; z-index: 2">
      <u-lst-layOut :showNavbar="false" :navbarOption="{ bgColor: 'rgba(255,255,255,1)', title: '发货' }" :color="{ statusBarHeightColor: '#fff' }">
        <template v-slot:header>
        <div style="height: 1px;background: #EFEFEF;width:100%"></div>
        </template>
        <template v-slot:main>
          <div class="" style="height: 100%; overflow-y: auto">
            <div class="bfff pb30 mt20 pl30 pt30 pr30">
              <div v-if="routeQuery.id" class="p1758006269 pl30 pr30 pb30 " style="background:#F7F8F8;border-radius: 10rpx">
                <u-lst-good :row="row"></u-lst-good>
              </div>
              <div v-else style="color: #595757;">
                <div class="f ">
                  <div class="" style="min-width: 150rpx"> 收货信息:</div>
                  <div class="dib">
                    <div class="di"> {{row.address_name}}， </div>
                    <div class="di "> {{row.address_tel}} ，</div>
                    <div class="di">{{row.address_province}}{{row.address_city}}{{row.address_area}}{{row.address_town}}{{row.address_storey}}{{row.address_house_number}}</div>
                  </div>
                </div>
                <div class=" f pt20 ">
                  <div class="" style="min-width: 150rpx"> 订单数量:</div>
                  <div style="color: #595757">{{row._orderNumTotal || 0}}个订单（共<div class="cD60012 dib">{{row._commodityNumTotal || 0}}</div> 件商品）</div>
                </div>
              </div>
            </div>
            <div class="mt20  ">
              <uv-form :labelStyle="{fontSize: '30rpx', color: '#595757', fontWeight: 400}" labelWidth="160rpx" labelPosition="left" :model="form" :rules="rules" ref="form">
                <div class="bfff pl30  pr30">
                  <uv-form-item label="快递单号" prop="freight_no" borderBottom>
                    <uv-input inputAlign="left" v-model="form.freight_no" disabledColor="#ffffff" placeholder="请输入快递单号" border="none" placeholderStyle="color:#9FA0A0;font-size:30rpx"></uv-input>
                    <template v-slot:right>
                      <!-- #ifndef H5 -->
                      <div @click="scanCodeTap" class="cD60012 f aic   fz28">
                        <div class="dib ">
                          <uv-icon color="#DE0012" size="40rpx" name="scan"></uv-icon>
                        </div>
                        <div style="min-height: 34rpx" class="lh1">扫码</div>
                      </div>
                      <!-- #endif -->
                    </template>
                  </uv-form-item>
                  <uv-form-item label="快递公司" prop="delivery_id" @click="openPopup(1)">
                    <div :class="!form.delivery_id && 'c9fa0a0'" class="fz30 pl10">
                      {{ showDeliveryTextFun(form.delivery_id || '') }}
                    </div>
                    <template v-slot:right>
                      <uv-icon size="30rpx" color="#9FA0A0" name="arrow-right"></uv-icon>
                    </template>
                  </uv-form-item>
                </div>
                <div class="bfff mt20 pl30  pr30">
                  <uv-form-item @click="openPopup(2)" prop="return_address_id" label="退货地址">
                    <template v-slot:right>
                      <uv-icon size="30rpx" color="#9FA0A0" name="arrow-right"></uv-icon>
                    </template>
                  </uv-form-item>
                </div>
                <div v-if="form.return_address_id" class="bfff pt20 pb30 pl30 pr30">
                  <div style="color: #595757;background: #F7F8F8;border-radius: 4rpx" class="fz28 pl30 pt30 pb30 pr30">{{ showAddressTextFun(form.return_address_id) }}</div>
                </div>
              </uv-form>
            </div>
          </div>
        </template>
        <template v-slot:footer>
          <div @click="submit" class="bfff common-footer p30 pt30 pb30 pr30">
            <button style="height: 90rpx" class="bD60012 w100 common-button cfff fz32">确认发货</button>
          </div>
        </template>
      </u-lst-layOut>

    </div>
    <uv-popup ref="addressPopup" mode="bottom" :safeAreaInsetBottom="false">
      <div style="background: #F7F8F8">
        <div class="position-r   f aic  jcc pb20 pt20">
          <div style="text-align: center;" class="w100 fz34">选择退货地址</div>
          <!-- <div @click="cancalTap" class="position-a" style="right: 30rpx;">
            <uv-icon size="40rpx" color="#9FA0A0" name="close"></uv-icon>
          </div> -->
        </div>
        <div style="border-top: 1px solid #EFEFEF" class="f pt20 pb20 aic jcc">
          <div class="fz28 cDE0012" @click="openPopup(3)">查看地址管理</div>
          <div style="margin-top: 2rpx">
            <uv-icon size="28rpx" color="#DE0012" name="arrow-right"></uv-icon>
          </div>
        </div>
        <div class="pl30 pb40  pr30">
          <div class="bfff pt30 pb30 pl20 mb30 pr30" style="border-radius: 12rpx;">
            <uv-radio-group @change="addressIdChange" activeColor="#DE0012" placement="column" iconPlacement="right" v-model="form.return_address_id">
              <uv-radio :name="item.id" v-for="(item, index) in addressList" :key="index">
                <div class="mt30 mb30  fac">
                  <uv-avatar size="65rpx" :text="updateInitial(item.name)" bg-color="#ffb34b"></uv-avatar>
                  <div class="pl20 ">
                    <div style="width: 90%" class=" fz30 single-line">{{item.fullAddress}}</div>
                    <div class="fz26 pt10" style="color: #ADADAE;">{{item.name}} {{item.tel}}</div>
                  </div>
                </div>
              </uv-radio>
            </uv-radio-group>
          </div>
        </div>
      </div>
    </uv-popup>
    <uv-popup ref="deliveryPopup" custom-style="height: 60vh;" mode="bottom" :safeAreaInsetBottom="false">
      <div style="background: #F7F8F8">
        <div class="position-r bfff  f aic  jcc pb20 pt20">
          <div style="text-align: center;" class="w100 fz34">选择快递</div>
          <div @click="$refs.deliveryPopup.close()" class="position-a" style="right: 30rpx;">
            <uv-icon size="40rpx" color="#9FA0A0" name="close"></uv-icon>
          </div>
        </div>
        <div class="oy " style="height: calc(60vh - 90rpx);">
          <div v-for="(item, index) in deliveryList" :key="index">
            <uv-sticky customNavHeight="0">
              <div style="background: #F7F8F8" class="pl30 pt20 pb20 fz32">{{ item.letter }}</div>
            </uv-sticky>
            <div class="pl20 pr40  bfff">
              <uv-radio-group labelSize="30rpx" labelColor="#333" @change="deliveryChange" activeColor="#DE0012" placement="column" iconPlacement="right" v-model="form.delivery_id">
                <div style="border-top: 1px solid #efefef;" class="  " v-for="(item1, index1) in item.words" :label="item1.title" :key="index + '-' + index1">
                  <uv-radio :name="item1.id">
                    <div class="pt20    pb20 fz28">{{ item1.title }}</div>
                  </uv-radio>
                </div>
              </uv-radio-group>
            </div>
          </div>
        </div>
      </div>
    </uv-popup>
  </div>
</template>

<script>
import myLayOutVue from "./components/layOut.vue";
import goodVue from "./components/good.vue";
import pageMixin from "./mixin/page.js";
import commonMixin from "./mixin/common.js";
import { orderDelivery, courierCompanyList, merchantsMergeShipments, returnAddressList, getDefault } from "@/api/merchant.js";
export default {
  components: {
    "u-lst-layOut": myLayOutVue,
    "u-lst-good": goodVue,
  },
  mixins: [commonMixin, pageMixin],
  data() {
    return {
      addressList: [],
      indexList: [],
      deliveryList: [],
      routeQuery: {},
      row: {},
      pageForm: {},
      form: {
        delivery_id: "",
        freight_no: "",
        return_address_id: "",
      },
      rules: {
        'delivery_id': { type: 'number', required: true, message: '请选择快递公司', trigger: ['blur', 'change'] },
        'freight_no': { type: 'string', required: true, message: '请输入快递单号', trigger: ['blur', 'change'] },
        'return_address_id': { type: 'number', required: true, message: '请选择退货地址', trigger: ['blur', 'change'] },
      },
    };
  },
  onLoad(options) {
    if (options) this.routeQuery = options
    this.initPage()
    this._getAddressList()
    this._getDefault()
  },
  onShow() {
    if (this.isOnShow) {
      this._getAddressList()
      this._getDefault()
    }
  },
  onHide() {
    this.isOnShow = true
  },
  methods: {
    _getDefault() {
      getDefault().then(res => {
        if (res.code == 200 && res.result.id) {
          this.$set(this.form, 'return_address_id', res.result.id)
        }
      })
    },
    submit() {
      this.$refs.form.validate().then(() => {
        uni.showLoading({ title: '请求中', mask: true })
        if (this.routeQuery.id) {
          orderDelivery(this.form).then(res => {
            if (res.code === 200) {
              uni.removeStorage({ key: 'storageForm' });
              uni.hideLoading()
              uni.$uv.toast('发货成功')
              setTimeout(() => {
                uni.navigateBack({ delta: 1 });
              }, 500);
            }
          })
        } else {
          merchantsMergeShipments(this.form).then(res => {
            if (res.code === 200) {
              uni.removeStorage({ key: 'storageForm' });
              uni.hideLoading()
              uni.$uv.toast('发货成功')
              setTimeout(() => {
                uni.navigateBack({ delta: 1 });
              }, 500);
            }
          })

        }
      })
    },
    openPopup(type) {
      if (type == 1) {
        if (!this.deliveryList.length) {
          this._courierCompanyList(() => { this.$refs.deliveryPopup.open() })
        } else {
          this.$refs.deliveryPopup.open()
        }
      }
      if (type == 2) {
        this.$refs.addressPopup.open()
      }
      if (type == 3) {
        this.$refs.addressPopup.close();
        uni.navigateTo({ url: '/pages-merchant/address/management' })
      }
    },
    addressIdChange(value) {
      this.$refs.addressPopup.close()
      this.$refs.form.validateField('return_address_id')
    },
    deliveryChange(value) {
      this.$refs.deliveryPopup.close()
      this.$refs.form.validateField('delivery_id')
    },
    scanCodeTap() {
      uni.scanCode({
        success: function (res) {
          console.log('条码类型：' + res.scanType);
          console.log('条码内容：' + res.result);
        }
      });
    },
    openTap(url) {

    },
    layOutChange(value) {
      this.pageForm = value
    },
    tabTap() {
    },
    _getAddressList(cb = () => { }) {
      if (!this.addressList.length) uni.showLoading({ title: '加载中', mask: true })
      returnAddressList().then(res => {
        if (res.code === 200) {
          if (!this.addressList.length) uni.hideLoading()
          this.addressList = res.result.map(item => {
            item.fullAddress = item.province + item.area + item.city + item.address
            item.isDefault = [item.is_default]
            return item
          })
          cb()
        }
      })
    },
    _courierCompanyList(cb = () => { }) {
      uni.showLoading({ title: '加载中', mask: true })
      courierCompanyList().then((res) => {
        if (res.code === 200) {
          uni.hideLoading()
          this.deliveryList = this.groupByFirstLetter(res.result)
          this.indexList = res.result
          cb()
        }
      })
    },
    initPage(cb = () => { }) {
      uni.getStorage({
        key: 'storageForm', success: res => {
          if (res.data) {
            if (this.routeQuery.id) {
              let { order_no, merchant_order_id, product_name, spec_values, price, product_image, cart_num, merchant_order, id } = JSON.parse(res.data)
              this.row = { order_no, merchant_order_id, product_name, spec_values, price, product_image, cart_num, merchant_order, id, status: 2 }
              this.$set(this.form, 'order_info_id', id)
              this.$set(this.form, 'merchant_order_id', merchant_order_id)
            } else {
              this.row = JSON.parse(res.data)
              this.$set(this.form, 'order_info_ids', this.row.order_info.map(i => i.id))
            }
          }
        }
      });
    },
    showAddressTextFun(id) {
      console.log(id)
      if (!this.addressList.length || !id) return
      let addressItem = this.addressList.find(i => i && i.id == id)
      if (addressItem) {
        let { name, tel, province, city, area, address } = addressItem
        return name + '，' + tel + '，' + province + city + area + address
      } else {
        this.$set(this.form, 'return_address_id', null)
        return ''
      }
    },
    showDeliveryTextFun(id) {
      if (!id || !this.indexList.length) {
        return '请选择快递公司'
      }
      let indexItem = this.indexList.find(item => {
        return item.id == id
      })
      if (indexItem) {
        let { title } = indexItem
        return title || '请选择快递公司'
      }
      return '请选择快递公司'
    },
    updateInitial(fullName) {
      if (fullName.trim()) {
        return fullName.trim().charAt(0);
      } else {
        return '';
      }
    },
    groupByFirstLetter(words) {
      const groups = {};
      words.forEach(word => {
        if (typeof word.title_en !== 'string' || word.title_en.trim() === '') return;
        const firstLetter = word.title_en[0].toUpperCase();

        if (!groups[firstLetter]) {
          groups[firstLetter] = [];
        }
        groups[firstLetter].push({ title_en: word.title_en, id: word.id, title: word.title });
      });
      Object.keys(groups).forEach(letter => {
        groups[letter].sort((a, b) => a.title_en.localeCompare(b.title_en));
      });

      const sortedGroups = [];
      Object.keys(groups).sort().forEach(letter => {
        sortedGroups.push({
          letter: letter,
          words: groups[letter]
        });
      });

      return sortedGroups;
    }

  },
};
</script>
<style>
page {
  background-color: #F7F8F8;
  color: #333333;
  font-size: 28rpx;
}
</style><style lang="scss" scoped>
@import "./common.scss";

.shipment {
  ::v-deep .p1758006269 {
    .p1758006210 {
      display: none !important;
    }
    .product_image {
      width: 80rpx !important;
      height: 80rpx !important;
      min-width: 80rpx !important;
    }
    .p1758006484 {
      padding-top: 10rpx !important;
    }
    .shipment-hidden {
      display: none !important;
    }
    .p1758006645 {
      padding: 30rpx 30rpx 0 0 !important;
      font-size: 28rpx !important;
    }
    .good-color {
      color: #595757 !important;
    }
    .p1758007407 {
      max-width: calc(100vw - 250rpx) !important;
    }
    .product_name {
      max-width: calc(100vw - 320rpx) !important;
      min-width: calc(100vw - 320rpx);
    }
  }
}
</style>
